from manimlib import *
from os import system

# 折线图demo
class scatter(Scene):
    # 添加标注
    def write_word(self, words, position=ORIGIN):
        t = Tex(words, color=GREEN_B)
        t.move_to(position)
        return t
    
    # 两点确定的直线方程
    def get_line_func(self, point1, point2):    
        if point1[0] == point2[0]:
            return lambda x : point1[0]
        else:
            k = (point2[1] - point1[1]) / (point2[0] - point1[0])
            b = point1[1] - k * point1[0]
            return lambda x : k * x + b

    def construct(self):
        # 点的序列，注意 np.array 后的逗号
        points = [
            np.array([57.18, 30.67, 0]),
            np.array([92.51, 46.35, 0]),
            np.array([114.35, 54.29, 0]),
            np.array([79.02, 46.38, 0]),
            np.array([100.85, 50.94, 0]),
            np.array([87.36, 48.39, 0])
        ]
        names = ["f1", "f2", "f3", "f4", "f5", "f6"]     # 点的名字
        
        # 创建坐标轴 width 和 height 能缩小图像的范围，坐标范围过大时需要调整
        axe_config = {
            "height" : 6, "width" : 10, 
            
            "x_range" : (0, 120, 10), 
            "y_range" : (0, 60, 5)
        }

        axes = Axes(**axe_config)
        axes.add_coordinate_labels()

        self.play(Write(axes))

        for i, _ in enumerate(points):
            if i < len(points) - 1:
                text = self.write_word(names[i], axes.c2p(points[i][0], points[i][1]))
                self.play(
                    ShowCreation(axes.get_graph(
                        function = self.get_line_func(points[i], points[i + 1]),
                        x_range = (points[i][0], points[i + 1][0]),
                        color = BLUE)),
                    Write(text)
                )

        text = self.write_word(names[-1], axes.c2p(points[-1][0], points[-1][1]))
        self.play(Write(text))

        ll = DashedLine(
            start = axes.c2p(0, 0),
            end = axes.c2p(93, 48),
        )
        self.play(ShowCreation(ll))

        ll1 = DashedLine(
            start = axes.c2p(0, 30.67),
            end = axes.c2p(100, 30.67),
        )
        self.play(ShowCreation(ll1))

        ll2 = DashedLine(
            start = axes.c2p(0, 46.35),
            end = axes.c2p(100, 46.35),
        )
        self.play(ShowCreation(ll2))
    
        dot = Dot(axes.c2p(79, 41), color=RED)
        self.play(FadeIn(dot, scale=0.5))
